package http.util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

import static io.netty.buffer.Unpooled.copiedBuffer;

public class FullHttpResponseUtil {

    public static void responseOK(String content, ChannelHandlerContext ctx) {
        response(HttpResponseStatus.OK, content, ctx);
    }

    public static void response(HttpResponseStatus status, String content, ChannelHandlerContext ctx) {
        if(!ctx.channel().isOpen()){//channel 已经被关闭了
            return;
        }
        ByteBuf byteBuf = copiedBuffer(content.getBytes());
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, byteBuf);
        response.headers().set("Content-Type", "text/plain;charset=UTF-8");
        response.headers().set("Content_Length", response.content().readableBytes());
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
